import {
  connectCardList,
  connectCard
} from '../../apis/card';
const app = getApp();

Page({
  data: {
    list: []
  },

  onLoad(options) {
    this.setData({
      ...options
    })
    this.getUpdateCard();
  },

  onReady() {
    wx.showToast({
      title: '请选择要关联的名片',
      icon: 'none',
      duration: 1500
    });
  },

  // 获取关联列表
  getUpdateCard() {
    connectCardList(this.data.cardId).then(res => {
      if (res.data.code === 200) {
        let {
          rows
        } = res.data;
        rows.forEach(v => {
          if (!new RegExp('^https://').test(v.avatar) && !new RegExp('^http://').test(v.avatar)) v.avatar = app.globalData.url + v.avatar;
          if (v.imageList) {
            v.imageList = v.imageList.map(val => {
              if (!new RegExp('^https://').test(val) && !new RegExp('^http://').test(val)) val = app.globalData.url + val;
              return val
            });
          };
        })
        this.setData({
          list: rows
        });
      };
    });
  },

  // 关联
  updateCard(e) {
    let {
      id
    } = e.currentTarget.dataset;
    wx.showModal({
      content: '确定关联此名片吗',
      title: '关联',
      success: res => {
        if (res.confirm) {
          connectCard(this.data.cardId, id).then(res => {
            if (res.data.code === 200) {
              wx.showToast({
                title: '关联成功',
                icon: 'success',
                duration: 1500,
                success: res => {
                  let timer = setTimeout(() => {
                    wx.switchTab({
                      url: '/pages/mailList/index',
                    });
                    clearTimeout(timer);
                  }, 1500);
                }
              });
            };
          });

        };
      }
    });
  },

  goToPreview(e) {
    let {
      id
    } = e.currentTarget.dataset;
    wx.navigateTo({
      url: `/pages/cardPreview/index?type=update&rCardId=${id}&cardId=${this.data.cardId}`,
    });
  },
})